import mimetypes
import os
import subprocess
import librosa
import os
import numpy as np
import soundfile as sf


def get_file_name(file_path):
    path, name = os.path.split(file_path)
    return name


def get_file_type(file_path):
    mime_type = mimetypes.guess_type(file_path)[0]
    if mime_type:
        return mime_type.split("/")[0]
    else:
        return None


def is_text(file_path):
    file_type = get_file_type(file_path)
    return file_type in ["text", "application"]


def is_audio(file_path):
    file_type = get_file_type(file_path)
    return file_type in ["audio"]


def is_video(file_path):
    file_type = get_file_type(file_path)
    return file_type in ["video"]


def split_video(input_file, audio_output_file, video_output_file):
    command = f'ffmpeg -i {input_file} -vn -acodec copy {audio_output_file} -an -vcodec copy {video_output_file}'
    return subprocess.call(command, shell=True) == 0


def merge_audio_video(audio_file, video_file, output_file):
    command = f'ffmpeg -i {audio_file} -i {video_file} -c:v copy -c:a aac -strict experimental {output_file}'
    return subprocess.call(command, shell=True) == 0


def convert216k(in_audio_file, out_audio_file, new_rate=16000):
    try:
        signal, sr = librosa.load(in_audio_file, sr=None)
        if int(sr) == new_rate:
            return in_audio_file
        new_signal = librosa.resample(signal, sr, new_rate)  #
        # librosa.output.write_wav(file_name, new_signal , new_sample_rate)
        sf.write(out_audio_file, new_signal, new_rate, subtype='PCM_24')
        print(f'{out_audio_file} has download.')
        return out_audio_file
    except:
        return None
